# GLOBALS:
#frForm = None
#otworzForm = None

import os
import time
import GuiUtils
from shutil import *
import SendKeys
from watsup.launcher import *
from watsup.winGuiAuto import *
from watsup import winGuiAuto

from djvu_ocr import settings

def findFineReaderMainWindow():
    forms = findTopWindows(wantedClass='FineReader9MainWindowClass')
    if forms:
        return forms[0]

def launchFineReader():
    # find an instance of FineReader9. If one isn't there, launch it
    global frForm
    frForm = findFineReaderMainWindow()
    if frForm:
        print "FineReader was already running."
    else:
        print "FineReader is starting...."        
        win32api.WinExec(settings.getProperty("finereader.path"))
        
        tryCount = 5
        while tryCount > 0: # give it a couple of more tries
            time.sleep(1) # wait for the application to initialize
            frForm = findFineReaderMainWindow()
            
            if frForm:
                break
            else:
                tryCount -= 1
                print "Can't find FineReader window. Giving it %s more tries." % (tryCount,)
                
        if frForm == None:
            print "Could not find FineReader main window. Script will exit."
            exit()
        else:
            print "FineReader window found."
            time.sleep(1)
            # Sometimes it happens that an additional popup messagebox is displayed when FR is started
            # saying something about files' recovery..
            popup = findFineReaderPopupWindow(frForm)
            if popup:
                # if so - cancel whatever there is.
                print "Found pop up window."
                GuiUtils.clickPopupButton(popup, "Nie")
                print "Decided to not recover data."
                
    return frForm

def findFineReaderPopupWindow(hwnd):
    allFRWindows = findTopWindows(wantedText="ABBYY FineReader")
    if len(allFRWindows) > 1:
        allFRWindows.remove(hwnd)
        return allFRWindows[0]
    return None

def startProcessingForTree(basePath):
    parentAlreadyProcessed = False
    
    createdPdfs = []
    for element in os.listdir(basePath):
        fullpath = os.path.join(basePath, element)
        if os.path.isdir(fullpath):
            createdPdfs.append(process(fullpath, basePath))
        elif not parentAlreadyProcessed:
            parentAlreadyProcessed = True
            createdPdfs.append(process(basePath, basePath))
            
    return createdPdfs
            
def openImages(files, dirPath):
    activateMenuItem(frForm, ('Plik', '&Otw\xf3rz PDF'))
#    activateMenuItem(frForm, ('File', 'Open PDF'))
    
    time.sleep(1.5)
    otworzForm = findTopWindow(wantedText=u'Otw\xf3rz obraz')
#    otworzForm = findTopWindow(wantedText = u'Open Image')
    
    time.sleep(0.5)
    otworzButtons = findControls(otworzForm, wantedText='Otw\xf3rz', wantedClass='Button')
    otworzButton = GuiUtils.selectTopMost(otworzButtons)    
    
    pathEdits = findControls(otworzForm, wantedClass='Edit')
    pathEdit = GuiUtils.selectTopMost(pathEdits)
    
    # at first navigate to the proper directory:
    time.sleep(0.5)
    setEditText(pathEdit, dirPath)
    time.sleep(0.5)
    clickButton(otworzButton)
    
    # then input all the filenames that apply:
    time.sleep(0.5)
    setEditText(pathEdit, files)
    time.sleep(0.5)
    clickButton(otworzButton)

def process(tiffDir, saveDir):
    listing = os.listdir(tiffDir)
    if len(listing) <= 0:
        print "No files found in: " + tiffDir
        return
    
    # save files list to a desc.txt
    descfile = open("desc.txt", "w")
    temp = ""
    for tiff in listing:
        filename, extension = os.path.splitext(tiff)
        if extension != ".db":
            temp += saveDir + "\\" + tiff + "\n"
        
    descfile.write(temp)
    descfile.close()
    
    filesList = ""
    
    if len(listing) == 1:
        filesList = listing[0]
    else:
        for tiff in listing:
            filesList += '"' + tiff + '" '
        
        filesList = filesList[:-1]
    
    openImages(filesList, tiffDir)

    time.sleep(0.5)
    
    waitTillProcessingDone("Zako\xf1czono Dodawanie stron do dokumentu")
        
    saved = saveAsPDF(saveDir, len(listing))
        
    time.sleep(1.5)
#    closePDFViewers()
    closeFRDocument()    
        
    print 'Files included in the output pdf: ' + filesList
    print 'PDF filename: ' + saved
    return saved
    
def waitTillProcessingDone(windowText):
    def findProgressWindow():
        return findTopWindows(wantedText=windowText)
    
    progressWindow = findProgressWindow()
    while progressWindow == None or len(progressWindow) <= 0:
        time.sleep(1)
        progressWindow = findProgressWindow()
    
    print "FineReader processing window found."
    
    while progressWindow != None and len(progressWindow) > 0:
        time.sleep(1)
        progressWindow = findProgressWindow()
        
    print "FineReader processing is finished."
    
def closePDFViewers():
    adobeReaderWindows = findTopWindows(wantedText="Adobe Reader")
    for viewer in adobeReaderWindows:
        win32gui.SendMessage(viewer, win32con.WM_CLOSE, 0, 0);
    
    print "All PDF viewers have been closed."    
    
def closeFRDocument():
    activateMenuItem(frForm, ("Plik", "Zamknij dokument"))
    time.sleep(0.5)
    popup = findFineReaderPopupWindow(frForm)
    if popup:
        print "Found pop up window."
        GuiUtils.clickPopupButton(popup, "Nie")
        print "Decided to not save FR document."
        
    print "FR Document closed."   
    
def saveAsPDF(tiffDir, pages):
    time.sleep(0.5)
    activateMenuItem(frForm, ('Plik', 'Zapisz jako', 'Dokument PDF'))
    #activateMenuItem(frForm, ('File', 'Save as', 'PDF Document'))
    
    time.sleep(0.5)
    zapiszWindow = findTopWindow(wantedText='Zapisz strony')
    #zapiszWindow = findTopWindow(wantedText='Save Pages')
    
    zapiszButton = findControl(zapiszWindow, wantedText='Zapisz', wantedClass='Button')
    
    outFilename = os.path.basename(tiffDir)
    pathEdit = findControl(zapiszWindow, wantedClass='Edit')
    
    frOutFolder = settings.getProperty("finereader.output.folder")
    pdfFilePath = frOutFolder + "\\" + outFilename
    
    setEditText(pathEdit, pdfFilePath)
    time.sleep(0.5)
        
    GuiUtils.clickButtonPost(zapiszButton)    
    time.sleep(0.5)
    
    popup = findFineReaderPopupWindow(frForm)
    if popup:
        copyfile(pdfFilePath + ".pdf", pdfFilePath + '_bkp.pdf') # backup
        time.sleep(2)
        GuiUtils.clickPopupButton(popup, "OK")
        time.sleep(0.5)
    
    if pages > 1:
        waitTillProcessingDone("Zako\xf1czono Zapisywanie w pliku")
        
    return pdfFilePath
